#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import argparse
import subprocess
import shutil

class mysqlLocal:

    def __init__(self, mysql_home, ip , port , user , password , backup_dir):
        self.ip = ip 
        self.port = port 
        self.user = user 
        self.password = password 
        self.backup_dir = backup_dir

        self.bin = mysql_home + '/bin'
        self.mysqldumpExec = self.bin + '/mysqldump'
    
    def runCmd(self, runCmd , viewCmd):
        #print("INFO:: Exec command :", viewCmd)
        child = subprocess.Popen(runCmd, shell=True, close_fds=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        result = None
        while True:
            line = child.stdout.readline(4096)
            if not line:
                break

            line = line.strip()
            line = line.decode('utf-8')
            if result is None:
                result = line
            else:
                result = result + "\n" + line

        # 把error错误，追加到cmd最后
        count = 0
        while True:
            if child.stderr is None:
                break

            line = child.stderr.readline(4096)
            if not line:
                break

            line = line.strip()
            line = line.decode('utf-8')
            if result is None:
                result = line
            elif count == 0:
                result = result + line
            else:
                result = result + "\n" + line
            count = count+1
        
        if(result is not None and 'ERROR' in result ) :
            print("ERROR:: Exec command failed. ", viewCmd)
            exit(1)
        return result

    def dumpAll(self , database):
        savepath = "{}/db_init/{}".format(self.backup_dir, database)
        savefile = "{}/db_init/{}/{}.sql".format(self.backup_dir,database,database)
        
        if(not os.path.exists(savepath)):
            os.makedirs(savepath)

        if( os.path.exists(savefile)):
            os.remove(savefile)

        runCmd ="{} -u{} -p'{}' -h {} -E -R --routines {} > {} ".format(self.mysqldumpExec , self.user , self.password , self.ip , database , savefile)
        viewCmd ="{} -u{} -p'{}' -h {} -E -R --routines {} > {} ".format(self.mysqldumpExec , self.user , "******" , self.ip , database , savefile )
        result= self.runCmd(runCmd , viewCmd)
        if ('Got error:' in result) :
            print("INFO:: Mysqldump {} success.".format(database))
        else:
            print("ERROR:: Mysqldump {} failed, {}".format( database , result ) )

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--mysql_home', default='', help='mysql install home')
    parser.add_argument('--ip', default='127.0.0.1', help='mysql db ip')
    parser.add_argument('--port', default=3306, help='mysql db port')
    parser.add_argument('--user', default='root', help='mysql db user')
    parser.add_argument('--password', default='', help='mysql db user password')
    parser.add_argument('--database_names', default='', help='database names, eg:codedriver')
    parser.add_argument('--backup_dir', default='', help='backup dir')

    
    args = parser.parse_args()
    ip = args.ip
    port = args.port
    user = args.user
    password = args.password
    database_names = args.database_names
    backup_dir = args.backup_dir
    mysql_home = args.mysql_home

    if ip is None  or ip == '':
        ip = '127.0.0.1'
    if port is None or port == '' :
        port = 3306 
    if user is None or user == '' :
        user = 'root' 
    if password is None or password == '' :
        password = 'zanyue$2012'
    
    if backup_dir is None or backup_dir == '':
        print("ERROR:: Must defind option --backup_dir")
        exit(1)

    if mysql_home is None or mysql_home == '':
        print("ERROR:: Must defind option --mysql_home")
        exit(1)
    
    if database_names is None or database_names == '':
        print("ERROR:: Must defind option --database_names")
        exit(1)
    
    local = mysqlLocal(mysql_home, ip , port , user , password , backup_dir)
    dbname_list = database_names.split(',')
    for db_name in dbname_list :
        print("INFO:: All dump databases {} start.".format(db_name))
        local.dumpAll(db_name)
        print("INFO:: All dump databases {} end.".format(db_name))

